package org.jeecg.modules.ganttTasks.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.ganttLinks.entity.GanttLinks;
import org.jeecg.modules.ganttLinks.service.IGanttLinksService;
import org.jeecg.modules.ganttTasks.entity.GanttTasks;
import org.jeecg.modules.ganttTasks.entity.Tasks;
import org.jeecg.modules.ganttTasks.service.IGanttTasksService;
import org.jeecg.modules.personalTask.entity.PersonalTask;
import org.jeecg.modules.personalTask.service.IPersonalTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 甘特图任务属性
 * @Author: jeecg-boot
 * @Date:   2023-08-23
 * @Version: V1.0
 */
@Api(tags="甘特图任务属性")
@RestController
@RequestMapping("/ganttTasks/ganttTasks")
@Slf4j
public class GanttTasksController extends JeecgController<GanttTasks, IGanttTasksService> {
	@Autowired
	private IGanttTasksService ganttTasksService;
	@Autowired
	private IGanttLinksService ganttLinksService;
	@Autowired
	private IPersonalTaskService personalTaskService;
	
	/**
	 * 分页列表查询
	 *
	 * @param ganttTasks
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "甘特图任务属性-分页列表查询")
	@ApiOperation(value="甘特图任务属性-分页列表查询", notes="甘特图任务属性-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(GanttTasks ganttTasks,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<GanttTasks> queryWrapper = QueryGenerator.initQueryWrapper(ganttTasks, req.getParameterMap());
		Page<GanttTasks> page = new Page<GanttTasks>(pageNo, pageSize);
		IPage<GanttTasks> pageList = ganttTasksService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@GetMapping("/getTask")
	public Result<?> getTask(){
		List<GanttTasks> data = ganttTasksService.list();
		List<GanttLinks> links = ganttLinksService.list();
//		log.info("data: {}", data);
		Tasks tasks = new Tasks(data, links);
		return Result.OK(tasks);
	}

	@GetMapping("/getUndone")
	public Result<?> getUndone(){
		QueryWrapper<GanttTasks> wrapper = new QueryWrapper<>();
		wrapper.ne("progress", 1);
		List<GanttTasks> data = ganttTasksService.list(wrapper);
		List<GanttLinks> links = ganttLinksService.list();
//		log.info("data: {}", data);
		Tasks tasks = new Tasks(data, links);
		return Result.OK(tasks);
	}

	@GetMapping("/getProject")
	public Result<?> getProject(){
		LambdaQueryWrapper<GanttTasks> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(GanttTasks::getType, "project");
		List<GanttTasks> list = ganttTasksService.list(wrapper);
		return Result.OK(list);
	}
	
	/**
	 *   添加
	 *
	 * @param ganttTasks
	 * @return
	 */
	@AutoLog(value = "甘特图任务属性-添加")
	@ApiOperation(value="甘特图任务属性-添加", notes="甘特图任务属性-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody GanttTasks ganttTasks) {
		boolean save = ganttTasksService.save(ganttTasks);
		if (save && "task".equals(ganttTasks.getType())){
			PersonalTask personalTask = getPersonalTask(ganttTasks);
			personalTask.setGanttId(ganttTasks.getId());
			personalTaskService.save(personalTask);
		}
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param ganttTasks
	 * @return
	 */
	@AutoLog(value = "甘特图任务属性-编辑")
	@ApiOperation(value="甘特图任务属性-编辑", notes="甘特图任务属性-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody GanttTasks ganttTasks) {
		boolean b = ganttTasksService.updateById(ganttTasks);
		if (b && "task".equals(ganttTasks.getType())){
			PersonalTask personalTask = getPersonalTask(ganttTasks);
			personalTaskService.updateById(personalTask);
		}
		return Result.OK("编辑成功!");
	}

	public PersonalTask getPersonalTask(GanttTasks ganttTasks){
		String id = ganttTasks.getId();
		if (id != null && !id.isEmpty()){
			LambdaQueryWrapper<PersonalTask> wrapper = Wrappers.lambdaQuery();
			wrapper.eq(PersonalTask::getGanttId, id);
			wrapper.eq(PersonalTask::getSign, 1);
			PersonalTask one = personalTaskService.getOne(wrapper);
			if (one != null){
				Date start = ganttTasks.getStartDate();
				Calendar c = Calendar.getInstance();
				c.setTime(start);
				c.add(Calendar.DAY_OF_MONTH, ganttTasks.getDuration()-1);
				one.setEndDate(c.getTime()).setSign(1)
						.setText(ganttTasks.getText())
						.setProjectId(ganttTasks.getParent())
						.setProgress(ganttTasks.getProgress())
						.setHeader(ganttTasks.getUsers())
						.setPriority(ganttTasks.getPriority());
				if (ganttTasks.getProgress() == 1){
					one.setStatus(2);
				}
				return one;
			}
		}
		PersonalTask personalTask = new PersonalTask();
		BeanUtils.copyProperties(ganttTasks, personalTask);
		Date start = personalTask.getStartDate();
		Calendar c = Calendar.getInstance();
		c.setTime(start);
		c.add(Calendar.DAY_OF_MONTH, personalTask.getDuration()-1);
		personalTask.setEndDate(c.getTime());
		personalTask.setStatus(1).setProgress(0D).setUpdateNum(0).setSign(1).setId(null)
				.setHeader(ganttTasks.getUsers()).setAssignor("管理员")
				.setParent(null).setProjectId(ganttTasks.getParent());
		return personalTask;
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "甘特图任务属性-通过id删除")
	@ApiOperation(value="甘特图任务属性-通过id删除", notes="甘特图任务属性-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		LambdaQueryWrapper<PersonalTask> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(PersonalTask::getGanttId, id);
		List<PersonalTask> list = personalTaskService.list(wrapper);
		List<String> ids = new LinkedList<>();
		for (PersonalTask personalTask : list){
			ids.add(personalTask.getId());
		}
		personalTaskService.removeByIds(ids);
		ganttTasksService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "甘特图任务属性-批量删除")
	@ApiOperation(value="甘特图任务属性-批量删除", notes="甘特图任务属性-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.ganttTasksService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "甘特图任务属性-通过id查询")
	@ApiOperation(value="甘特图任务属性-通过id查询", notes="甘特图任务属性-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		GanttTasks ganttTasks = ganttTasksService.getById(id);
		if(ganttTasks==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(ganttTasks);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param ganttTasks
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GanttTasks ganttTasks) {
        return super.exportXls(request, ganttTasks, GanttTasks.class, "甘特图任务属性");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GanttTasks.class);
    }

}
